﻿using Sustainalytics.Entities;
using Sustainalytics.Portfolios.BL;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;

namespace Sustainalytics.Alerts.AlertsEngine
{
    public class PortfolioCompanyCache : IPortfolioCompanyCache
    {
        private ConcurrentDictionary<Guid, List<Guid>> _portfolioDict;
        private IPorfolioNamesCache _porfolioNamesCache;

        
        public PortfolioCompanyCache(IPorfolioNamesCache porfolioNamesCache)
        {
            _portfolioDict = new ConcurrentDictionary<Guid, List<Guid>>();
            _porfolioNamesCache = porfolioNamesCache;
        }
        public IList<Guid> GetCompaniesForPortfolio(Guid portId, List<Guid> companiesWithAlerts, IPortfolioReadHandler portfolioManager)
        {
            if (!_portfolioDict.ContainsKey(portId))
            {
                var companies = portfolioManager.GetCompanyIdsByPortfolio(portId).ToList();
                companies = companies.Intersect(companiesWithAlerts).ToList();

                _portfolioDict[portId] = companies;
            }
            return _portfolioDict[portId];
        }
        public Dictionary<Guid, string> GetPortfolioListForCompanies(SubscribeToPortfolio subscriber, List<Guid> companiesEnabledForFeature, IPortfolioReadHandler portfolioManager)
        {
            //prepare company2portfolio
            var company2portfolio = new Dictionary<Guid, List<string>>();
            bool bAllCompanies = false;
            subscriber.PortfolioIds.ForEach(portId =>
                {
                    if (portId == Guid.Empty)//all companies
                    {
                        bAllCompanies = true;
                    }
                    else
                    {
                _portfolioDict[portId].ForEach(compId =>
                {
                    var portName = _porfolioNamesCache.GetPortfolioName(portId, portfolioManager);
                    if (company2portfolio.ContainsKey(compId))
                    {
                        company2portfolio[compId].Add(portName);
                    }
                    else
                    {
                        company2portfolio.Add(compId, new List<string>() { portName });
                    }
                        });
                    }
                });

            if (bAllCompanies)
            {
                var companiesInAllComp = companiesEnabledForFeature.Except(company2portfolio.Keys).ToList();

                company2portfolio.Keys.ToList().ForEach(compId => company2portfolio[compId].Add(PorfolioNamesCache.AllCompaniesLabel));
                companiesInAllComp.ForEach(compId => company2portfolio.Add(compId, new List<string>() { PorfolioNamesCache.AllCompaniesLabel }));
            }

            return company2portfolio.ToDictionary(c => c.Key, c => c.Value.Aggregate((i, j) => i + ", " + j));
        }
    }
}
